package com.community.config.shiro;

import com.community.entity.Right;
import com.community.entity.Role;
import com.community.entity.User;
import com.community.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm { //安全数据源
    @Resource
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        User user = userService.getUserAndRoleByAccount(usrName);
        if (user == null) {
            throw new UnknownAccountException(); //账号错误
        }
        /*if (user.getUsrFlag() == null || user.getUsrFlag().intValue() == 0) {
            throw new LockedAccountException(); //账号锁定
        }*/
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,//身份(根据用户名查询数据库获得的用户)
                user.getPassword(),//凭证(查询数据库获得的密码)
                getName()//Realm 对象的名称
        );
        //返回身份信息
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm.doGetAuthorizationInfo 获取权限信息！");
        //获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //动态获取权限
        Role role = user.getRole();
        if (role != null) {
            System.out.println("************-----动态获取权限-----****************");
            System.out.println("User*******");
            System.out.println(user.toString());
            System.out.println("Role*******");
            System.out.println(user.getRole());
            System.out.println("Rights*******");
            System.out.println(user.getRole().getRights());

            info.addRole(user.getRole().getRoleName());
            Set<Right> rights = role.getRights();
            if (rights != null && rights.size() > 0) {
                for (Right right : rights) {
                    System.out.println("用户授权的权限:" + right.getRightText());
                    info.addStringPermission(right.getRightText());
                }
            }
        }

        return info;
    }
}
